{% extends "admin/base.html" %}

{% block title %}{% if post %}编辑文章{% else %}写新文章{% endif %}{% endblock %}

{% block page_title %}{% if post %}编辑文章{% else %}写新文章{% endif %}{% endblock %}

{% block extra_css %}
<style>
/* 文章编辑页面样式 */
.post-edit-container {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    overflow: hidden;
}

.post-edit-header {
    padding: 1.5rem 2rem;
    border-bottom: 1px solid #e1e8ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}

.post-edit-header h1 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.25rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.post-edit-actions {
    display: flex;
    gap: 1rem;
    align-items: center;
}

.btn-save {
    background: #28a745;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.btn-save:hover {
    background: #218838;
    color: white;
    text-decoration: none;
}

.btn-publish {
    background: #007bff;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    cursor: pointer;
}

.btn-publish:hover {
    background: #0056b3;
    color: white;
    text-decoration: none;
}

.btn-cancel {
    background: #6c757d;
    color: white;
    padding: 0.5rem 1rem;
    border: none;
    border-radius: 6px;
    text-decoration: none;
    font-weight: 500;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-cancel:hover {
    background: #5a6268;
    color: white;
    text-decoration: none;
}

/* 表单区域 */
.post-edit-form {
    padding: 2rem;
}

.form-row {
    display: flex;
    flex-direction: column;
    gap: 2rem;
    margin-bottom: 2rem;
}

.form-main {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.form-sidebar {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

/* 表单组样式 */
.form-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.form-group label {
    font-weight: 600;
    color: #495057;
    font-size: 0.875rem;
}

.form-group input,
.form-group textarea,
.form-group select {
    padding: 0.75rem;
    border: 1px solid #ced4da;
    border-radius: 8px;
    font-size: 0.875rem;
    transition: all 0.3s ease;
    font-family: inherit;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus {
    outline: none;
    border-color: #007bff;
    box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.form-group textarea {
    resize: vertical;
    min-height: 120px;
}

/* 标题输入框 */
.title-input {
    font-size: 1.25rem;
    font-weight: 600;
    padding: 1rem;
}

/* 内容编辑器 */
.content-editor {
    min-height: 800px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    line-height: 1.6;
}

/* 摘要输入框 */
.excerpt-textarea {
    min-height: 100px;
    font-size: 0.875rem;
    line-height: 1.5;
}

/* 封面图片区域 */
.cover-image-group {
    position: relative;
}

.cover-image-preview {
    width: 100%;
    height: 200px;
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f9fa;
    margin-top: 0.5rem;
    overflow: hidden;
}

.cover-image-preview img {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
    border-radius: 6px;
}


.cover-image-actions {
    display: flex;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.btn-upload {
    background: #007bff;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-size: 0.875rem;
    cursor: pointer;
    transition: background 0.3s ease;
}

.btn-upload:hover {
    background: #0056b3;
}

.btn-remove {
    background: #dc3545;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-size: 0.875rem;
    cursor: pointer;
    transition: background 0.3s ease;
}

.btn-remove:hover {
    background: #c82333;
}

/* 标签选择器样式 */
.tag-select-container {
    margin-bottom: 0.5rem;
}

.tag-select {
    width: 100%;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 6px;
    font-size: 0.875rem;
    background: white;
    outline: none;
    transition: border-color 0.3s ease;
}

.tag-select:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.selected-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    min-height: 40px;
    padding: 0.5rem;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    background: #f8f9fa;
}

.selected-tag {
    background: #007bff;
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    animation: slideIn 0.3s ease;
}

.selected-tag-remove {
    background: none;
    border: none;
    color: white;
    cursor: pointer;
    font-size: 0.875rem;
    padding: 0;
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.3s ease;
}

.selected-tag-remove:hover {
    background: rgba(255, 255, 255, 0.2);
}

.empty-tags {
    color: #6c757d;
    font-size: 0.875rem;
    font-style: italic;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

/* 状态和选项区域 */
.status-options {
    background: #f8f9fa;
    padding: 1.5rem;
    border-radius: 8px;
    border: 1px solid #e9ecef;
}

.status-options h3 {
    margin: 0 0 1rem 0;
    font-size: 1rem;
    color: #495057;
    font-weight: 600;
}

.option-group {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-top: 1rem;
}

.option-group:last-child {
    margin-bottom: 0;
}

.option-group input[type="checkbox"] {
    width: 18px;
    height: 18px;
    margin: 0;
}

.option-group label {
    font-size: 0.875rem;
    color: #495057;
    cursor: pointer;
    margin: 0;
}

/* 分类选择 */
.category-select {
    width: 100%;
}

/* 标签管理区域 */
.tags-input {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    border-radius: 8px;
    min-height: 40px;
    align-items: center;
}

.tag-item {
    background: #007bff;
    color: white;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.tag-remove {
    background: none;
    border: none;
    color: white;
    cursor: pointer;
    font-size: 0.875rem;
    padding: 0;
    width: 16px;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background 0.3s ease;
}

.tag-remove:hover {
    background: rgba(255, 255, 255, 0.2);
}

.tag-input {
    border: none;
    outline: none;
    flex: 1;
    min-width: 100px;
    font-size: 0.875rem;
}

/* 封面图片区域 */
.cover-image-group {
    position: relative;
}

/* 封面模式选择器 */
.cover-mode-selector {
    display: flex;
    gap: 0.5rem;
    margin: 0.5rem 0;
}

.mode-btn {
    flex: 1;
    padding: 0.5rem;
    border: 1px solid #ced4da;
    background: #fff;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.25rem;
    font-size: 0.875rem;
    color: #495057;
}

.mode-btn:hover {
    background: #f8f9fa;
    border-color: #007bff;
}

.mode-btn.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

/* 封面图片预览区域 */
.cover-image-preview {
    width: 100%;
    min-height: 200px;
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f8f9fa;
    margin-top: 0.5rem;
    overflow: hidden;
    position: relative;
}

/* 单图模式 */
.cover-image-preview.single-mode {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cover-image-preview.single-mode img {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

/* 三图模式 */
.cover-image-preview.triple-mode {
    height: 120px;
    gap: 0.5rem;
    padding: 0.5rem;
}

.cover-image-preview.triple-mode img {
    flex: 1;
    height: 100%;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #dee2e6;
}

.cover-image-preview.empty,
.cover-image-preview .empty {
    color: #6c757d;
    font-size: 0.875rem;
    flex-direction: column;
    gap: 0.5rem;
    align-items: center;
    justify-content: center;
    display: flex;
}

.cover-image-preview.empty i,
.cover-image-preview .empty i {
    font-size: 2rem;
    margin-bottom: 0.5rem;
}

.cover-image-preview.empty p,
.cover-image-preview .empty p {
    margin: 0;
    text-align: center;
}

.cover-image-actions {
    display: flex;
    gap: 0.5rem;
    margin-top: 0.5rem;
}

.btn-upload {
    background: #007bff;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    font-size: 0.875rem;
    cursor: pointer;
    transition: background 0.3s ease;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
}

.btn-upload:hover {
    background: #0056b3;
}

/* 保存状态指示器 */
.save-status {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    font-weight: 500;
    z-index: 1000;
    transition: all 0.3s ease;
    transform: translateX(100%);
}

.save-status.show {
    transform: translateX(0);
}

.save-status.saving {
    background: #ffc107;
    color: #212529;
}

.save-status.saved {
    background: #28a745;
    color: white;
}

.save-status.error {
    background: #dc3545;
    color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .post-edit-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .post-edit-actions {
        justify-content: center;
    }
    
    .content-editor {
        min-height: 500px;
    }
}

/* 编辑器容器 */
.editor-container {
    border: 1px solid #e9ecef;
    border-radius: 6px;
    overflow: hidden;
}

/* 工具栏分隔符 */
.toolbar-divider {
    width: 1px;
    height: 24px;
    background: #dee2e6;
    margin: 0 0.5rem;
}

/* 编辑器区域 */
.editor-area {
    position: relative;
    height: 500px;
}

.editor-pane, .preview-pane {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
}

.preview-pane {
    background: white;
}

.content-editor {
    flex: 1;
    border: none;
    padding: 1rem;
    font-size: 0.875rem;
    line-height: 1.6;
    outline: none;
    background: white;
    min-height: 400px;
    overflow-y: auto;
}

.content-editor:empty:before {
    content: attr(placeholder);
    color: #6c757d;
    font-style: italic;
}

.preview-content {
    flex: 1;
    padding: 1rem;
    overflow-y: auto;
    background: white;
    font-size: 0.875rem;
    line-height: 1.6;
    min-height: 300px;
}

/* Markdown预览样式 */
.preview-content h1, .preview-content h2, .preview-content h3, 
.preview-content h4, .preview-content h5, .preview-content h6 {
    margin-top: 1.5rem;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #2c3e50;
}

.preview-content h1 { font-size: 1.5rem; }
.preview-content h2 { font-size: 1.25rem; }
.preview-content h3 { font-size: 1.125rem; }
.preview-content h4 { font-size: 1rem; }
.preview-content h5 { font-size: 0.875rem; }
.preview-content h6 { font-size: 0.75rem; }

.preview-content p {
    margin-bottom: 1rem;
    color: #495057;
}

.preview-content strong {
    font-weight: 600;
    color: #2c3e50;
}

.preview-content em {
    font-style: italic;
    color: #6c757d;
}

.preview-content u {
    text-decoration: underline;
}

.preview-content code {
    background: #f8f9fa;
    padding: 0.125rem 0.25rem;
    border-radius: 3px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 0.8em;
    color: #e83e8c;
}

.preview-content pre {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 6px;
    overflow-x: auto;
    margin-bottom: 1rem;
}

.preview-content pre code {
    background: none;
    padding: 0;
    color: #495057;
}

.preview-content a {
    color: #007bff;
    text-decoration: none;
}

.preview-content a:hover {
    text-decoration: underline;
}

.preview-content img {
    max-width: 100%;
    height: auto;
    border-radius: 6px;
    margin: 0.5rem 0;
}

.preview-content blockquote {
    border-left: 4px solid #007bff;
    padding-left: 1rem;
    margin: 1rem 0;
    color: #6c757d;
    font-style: italic;
}

.preview-content ul, .preview-content ol {
    margin-bottom: 1rem;
    padding-left: 1.5rem;
}

.preview-content li {
    margin-bottom: 0.25rem;
}

.preview-content hr {
    border: none;
    border-top: 1px solid #e9ecef;
    margin: 2rem 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .content-editor {
        min-height: 300px;
    }
    
    .preview-content {
        min-height: 250px;
    }
}

/* 编辑器工具栏 */
.editor-toolbar {
    display: flex;
    gap: 0.5rem;
    padding: 0.75rem;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-bottom: none;
    border-radius: 8px 8px 0 0;
    flex-wrap: wrap;
}

.toolbar-btn {
    background: white;
    border: 1px solid #ced4da;
    padding: 0.5rem;
    border-radius: 4px;
    cursor: pointer;
    color: #495057;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
}

.toolbar-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
}

.toolbar-btn.active {
    background: #007bff;
    color: white;
    border-color: #007bff;
}

.toolbar-group {
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.toolbar-select {
    background: white;
    border: 1px solid #ced4da;
    border-radius: 4px;
    padding: 0.25rem 0.5rem;
    font-size: 0.75rem;
    color: #495057;
    cursor: pointer;
    outline: none;
    transition: border-color 0.2s ease;
    min-width: 60px;
}

.toolbar-select:focus {
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

/* 自定义确认对话框样式 */
.custom-confirm-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: fadeIn 0.3s ease;
}

.custom-confirm-dialog {
    background: white;
    border-radius: 12px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    max-width: 400px;
    width: 90%;
    animation: slideIn 0.3s ease;
}

.custom-confirm-header {
    padding: 1.5rem 1.5rem 1rem;
    border-bottom: 1px solid #e9ecef;
}

.custom-confirm-header h3 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.custom-confirm-header i {
    color: #ffc107;
    font-size: 1.2rem;
}

.custom-confirm-body {
    padding: 1.5rem;
}

.custom-confirm-body p {
    margin: 0;
    color: #495057;
    line-height: 1.5;
    font-size: 0.95rem;
}

.custom-confirm-footer {
    padding: 1rem 1.5rem 1.5rem;
    display: flex;
    gap: 0.75rem;
    justify-content: flex-end;
}

.btn-confirm-cancel,
.btn-confirm-ok {
    padding: 0.5rem 1.25rem;
    border: none;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 80px;
}

.btn-confirm-cancel {
    background: #6c757d;
    color: white;
}

.btn-confirm-cancel:hover {
    background: #5a6268;
}

.btn-confirm-ok {
    background: #dc3545;
    color: white;
}

.btn-confirm-ok:hover {
    background: #c82333;
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 1;
    }
}

@keyframes slideIn {
    from {
        transform: translateY(-20px);
        opacity: 0;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

/* 素材选择模态框样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: fadeIn 0.3s ease;
}

.modal-dialog {
    background: white;
    border-radius: 12px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
    max-width: 800px;
    width: 90%;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    animation: slideIn 0.3s ease;
}

.modal-header {
    padding: 1.5rem 1.5rem 1rem;
    border-bottom: 1px solid #e9ecef;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
    color: #2c3e50;
    font-size: 1.1rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.modal-close {
    background: none;
    border: none;
    font-size: 1.2rem;
    color: #6c757d;
    cursor: pointer;
    padding: 0.25rem;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.modal-close:hover {
    background: #f8f9fa;
    color: #495057;
}

.modal-body {
    padding: 1.5rem;
    flex: 1;
    overflow-y: auto;
}

.modal-footer {
    padding: 1rem 1.5rem 1.5rem;
    display: flex;
    gap: 0.75rem;
    justify-content: flex-end;
    border-top: 1px solid #e9ecef;
}


.btn-cancel {
    background: #6c757d;
    color: white;
    border: none;
    padding: 0.5rem 1.25rem;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-cancel:hover {
    background: #5a6268;
}

.btn-confirm {
    background: #007bff;
    color: white;
    border: none;
    padding: 0.5rem 1.25rem;
    border-radius: 6px;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.btn-confirm:hover {
    background: #0056b3;
}

.btn-confirm:disabled {
    background: #6c757d;
    cursor: not-allowed;
}
</style>
{% endblock %}

{% block content %}
<div class="post-edit-container">
    <!-- 页面头部 -->
    <div class="post-edit-header">
        <h1>
            <i class="fas fa-{% if post %}edit{% else %}plus{% endif %}"></i>
            {% if post %}编辑文章{% else %}写新文章{% endif %}
        </h1>
        <div class="post-edit-actions">
            <button type="button" class="btn-save" onclick="saveDraft()">
                <i class="fas fa-save"></i>
                保存草稿
            </button>
            <button type="button" class="btn-publish" onclick="publishPost()">
                <i class="fas fa-paper-plane"></i>
                发布文章
            </button>
            <button type="button" class="btn-cancel" onclick="cancelEdit()">
                <i class="fas fa-times"></i>
                取消
            </button>
        </div>
    </div>
    
    <!-- 编辑表单 -->
    <form id="post-form" class="post-edit-form">
        <div class="form-row">
            <!-- 主要内容区域 -->
            <div class="form-main">
                <!-- 文章标题 -->
                <div class="form-group">
                    <label for="title">文章标题 *</label>
                    <input type="text" id="title" name="title" class="title-input" 
                           value="{{ post.title if post else '' }}" 
                           placeholder="请输入文章标题..." required>
                </div>
                
                <!-- 文章内容 -->
                <div class="form-group">
                    <label for="content">文章内容 *</label>
                    <div class="editor-container">
            <!-- 编辑器工具栏 -->
            <div class="editor-toolbar">
                <!-- 文字按钮 -->
                <div class="toolbar-group">
                    <button type="button" class="toolbar-btn" onclick="focusEditor()" title="输入文字">
                        <i class="fas fa-font"></i>
                    </button>
                </div>
            </div>
                        
                        <!-- 编辑器区域 -->
                        <div class="editor-area">
                            <div id="editor-pane" class="editor-pane">
                                <div id="content" name="content" class="content-editor" contenteditable="true" 
                                     placeholder="请输入文章内容..." required>{{ post.content if post else '' }}</div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 文章摘要 -->
                <div class="form-group">
                    <label for="excerpt">文章摘要</label>
                    <textarea id="excerpt" name="excerpt" class="excerpt-textarea" 
                              placeholder="请输入文章摘要（可选，留空将自动截取文章前200字）...">{{ post.excerpt if post else '' }}</textarea>
                </div>
            </div>
            
            <!-- 侧边栏 -->
            <div class="form-sidebar">
                <!-- 发布状态和选项 -->
                <div class="status-options">
                    <h3>发布设置</h3>
                    
                    <div class="form-group">
                        <label for="status">发布状态</label>
                        <select id="status" name="status" class="form-control">
                            <option value="draft" {% if not post or post.status == 'draft' %}selected{% endif %}>草稿</option>
                            <option value="published" {% if post and post.status == 'published' %}selected{% endif %}>已发布</option>
                            <option value="archived" {% if post and post.status == 'archived' %}selected{% endif %}>已归档</option>
                        </select>
                    </div>
                    
                    <div class="option-group">
                        <input type="checkbox" id="is_featured" name="is_featured" 
                               {% if post and post.is_featured %}checked{% endif %}>
                        <label for="is_featured">设为精选文章</label>
                    </div>
                    
                    <div class="option-group">
                        <input type="checkbox" id="allow_comments" name="allow_comments" 
                               {% if not post or post.allow_comments %}checked{% endif %}>
                        <label for="allow_comments">允许评论</label>
                    </div>
                </div>
                
                <!-- 分类选择 -->
                <div class="form-group">
                    <label for="category_id">文章分类</label>
                    <select id="category_id" name="category_id" class="category-select form-control">
                        <option value="">选择分类</option>
                        {% for category in categories %}
                        <option value="{{ category.id }}" 
                                {% if post and post.category_id == category.id %}selected{% endif %}>
                            {{ category.name }}
                        </option>
                        {% endfor %}
                    </select>
                </div>
                
                <!-- 标签管理 -->
                <div class="form-group">
                    <label for="tags">文章标签</label>
                    <div class="tag-select-container">
                        <select id="tag-select" class="tag-select" onchange="addTagFromSelect()">
                            <option value="">请选择标签...</option>
                        {% for tag in existing_tags %}
                            <option value="{{ tag.name }}">{{ tag.name }}</option>
                        {% endfor %}
                        </select>
                        <button type="button" class="btn-upload" onclick="addNewTag()" style="margin-top: 0.5rem;">
                            <i class="fas fa-plus"></i>
                            添加新标签
                        </button>
                    </div>
                    <div class="selected-tags" id="selected-tags">
                        <!-- 已选择的标签将显示在这里 -->
                    </div>
                </div>
                
                <!-- 封面图片 -->
                <div class="form-group cover-image-group">
                    <label for="cover_image">封面图片</label>
                    
                    <!-- 封面模式选择 -->
                    <div class="cover-mode-selector">
                        <button type="button" class="mode-btn active" data-mode="none" onclick="setCoverMode('none')">
                            <i class="fas fa-ban"></i>
                            无图
                        </button>
                        <button type="button" class="mode-btn" data-mode="single" onclick="setCoverMode('single')">
                            <i class="fas fa-image"></i>
                            单图
                        </button>
                        <button type="button" class="mode-btn" data-mode="triple" onclick="setCoverMode('triple')">
                            <i class="fas fa-images"></i>
                            三图
                        </button>
                    </div>
                    
                    <!-- 封面图片预览区域 -->
                    <div class="cover-image-preview" id="cover-preview">
                            <div class="empty">
                                <i class="fas fa-image"></i>
                            <p>请选择封面模式</p>
                            </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="cover-image-actions">
                        <button type="button" class="btn-upload" onclick="document.getElementById('cover-image-upload').click()">
                            <i class="fas fa-upload"></i>
                            上传图片
                        </button>
                        <input type="file" id="cover-image-upload" accept="image/*" style="display: none;" onchange="uploadCoverImage(this)">
                        <button type="button" class="btn-remove" onclick="removeCoverImage()" style="display: none;">
                            <i class="fas fa-trash"></i>
                            移除
                        </button>
                    </div>
                    
                    <!-- 隐藏字段存储封面图片数据 -->
                    <input type="hidden" id="cover_image" name="cover_image" 
                           value="{{ post.cover_image if post else '' }}">
                    <input type="hidden" id="cover_mode" name="cover_mode" 
                           value="{{ post.cover_mode if post else 'none' }}">
                </div>
            </div>
        </div>
    </form>
</div>

<!-- 保存状态指示器 -->
<div id="save-status" class="save-status"></div>

<!-- 自定义确认对话框 -->
<div id="custom-confirm" class="custom-confirm-overlay" style="display: none;">
    <div class="custom-confirm-dialog">
        <div class="custom-confirm-header">
            <h3><i class="fas fa-exclamation-triangle"></i> 确认操作</h3>
        </div>
        <div class="custom-confirm-body">
            <p id="confirm-message">您确定要执行此操作吗？</p>
        </div>
        <div class="custom-confirm-footer">
            <button type="button" class="btn-confirm-cancel" id="btn-confirm-cancel">取消</button>
            <button type="button" class="btn-confirm-ok" id="btn-confirm-ok">确定</button>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
// 文章编辑相关功能
let currentTags = {{ (post.tags|map(attribute='name')|list if post else [])|tojson|safe }};
let allTags = {{ existing_tags|map(attribute='name')|list|tojson|safe }};
let autoSaveInterval;
let confirmCallback = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    renderSelectedTags();
    setupAutoSave();
    setupFormValidation();
    setupCustomConfirm();
    initializeCoverImages();
    initializeContentEditor();
});

// 初始化内容编辑器
function initializeContentEditor() {
    const contentEditor = document.getElementById('content');
    if (contentEditor) {
        // 设置占位符
        contentEditor.setAttribute('placeholder', '请输入文章内容...');
        
        // 添加输入事件监听
        contentEditor.addEventListener('input', function() {
            // 可以在这里添加实时保存逻辑
        });
        
        // 添加键盘快捷键
        contentEditor.addEventListener('keydown', function(e) {
            // Ctrl+S 保存
            if (e.ctrlKey && e.key === 's') {
                e.preventDefault();
                saveDraft(true);
            }
        });
    }
}

// 编辑器工具栏功能
function focusEditor() {
    const contentEditor = document.getElementById('content');
    contentEditor.focus();
    
    // 如果编辑器为空，插入一个段落
    if (contentEditor.textContent.trim() === '') {
        const p = document.createElement('p');
        p.innerHTML = '&nbsp;';
        contentEditor.appendChild(p);
        
        // 将光标放在段落内
        const range = document.createRange();
        range.setStart(p, 0);
        range.setEnd(p, 0);
        
        const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

function updatePreview() {
    const contentEditor = document.getElementById('content');
    const previewContent = document.getElementById('preview-content');
    const markdown = contentEditor.value;
    
    // 简单的Markdown解析
    const html = parseMarkdown(markdown);
    previewContent.innerHTML = html;
}

function parseMarkdown(markdown) {
    if (!markdown) return '<p class="text-muted">开始输入内容以查看预览...</p>';
    
    let html = markdown
        // 标题
        .replace(/^### (.*$)/gim, '<h3>$1</h3>')
        .replace(/^## (.*$)/gim, '<h2>$1</h2>')
        .replace(/^# (.*$)/gim, '<h1>$1</h1>')
        
        // 粗体和斜体
        .replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/gim, '<em>$1</em>')
        
        // 下划线
        .replace(/<u>(.*?)<\/u>/gim, '<u>$1</u>')
        
        // 代码
        .replace(/`(.*?)`/gim, '<code>$1</code>')
        
        // 链接
        .replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2" target="_blank">$1</a>')
        
        // 图片
        .replace(/!\[([^\]]*)\]\(([^)]+)\)/gim, '<img src="$2" alt="$1" style="max-width: 100%; height: auto;">')
        
        // 换行
        .replace(/\n/gim, '<br>');
    
    // 处理段落
    html = html.split('<br>').map(line => {
        line = line.trim();
        if (line && !line.startsWith('<h') && !line.startsWith('<img') && !line.startsWith('<code') && !line.startsWith('<a')) {
            return `<p>${line}</p>`;
        }
        return line;
    }).join('');
    
    return html;
}

// 初始化封面图片
function initializeCoverImages() {
    const coverMode = document.getElementById('cover_mode').value || 'none';
    const coverImage = document.getElementById('cover_image').value;
    
    currentCoverMode = coverMode;
    
    // 设置按钮状态
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-mode="${coverMode}"]`).classList.add('active');
    
    // 解析现有图片
    if (coverImage) {
        if (coverMode === 'single') {
            coverImages = [coverImage];
        } else if (coverMode === 'triple') {
            try {
                coverImages = JSON.parse(coverImage);
            } catch (e) {
                coverImages = [coverImage];
            }
        }
    }
    
    updateCoverPreview();
}

// 设置自定义确认对话框
function setupCustomConfirm() {
    const overlay = document.getElementById('custom-confirm');
    const cancelBtn = document.getElementById('btn-confirm-cancel');
    const okBtn = document.getElementById('btn-confirm-ok');
    
    // 先移除可能存在的旧事件监听器
    overlay.removeEventListener('click', handleOverlayClick);
    cancelBtn.removeEventListener('click', handleCancelClick);
    okBtn.removeEventListener('click', handleOkClick);
    
    // 点击遮罩层关闭
    overlay.addEventListener('click', handleOverlayClick);
    
    // 取消按钮
    cancelBtn.addEventListener('click', handleCancelClick);
    
    // 确定按钮
    okBtn.addEventListener('click', handleOkClick);
}

// 事件处理函数
function handleOverlayClick(e) {
    if (e.target === e.currentTarget) {
        hideCustomConfirm();
    }
}

function handleCancelClick() {
    hideCustomConfirm();
}

function handleOkClick() {
    if (confirmCallback) {
        confirmCallback();
    }
    hideCustomConfirm();
}

// 标签相关功能
function addTagFromSelect() {
    const select = document.getElementById('tag-select');
    const selectedTag = select.value;
    
    if (selectedTag && !currentTags.includes(selectedTag)) {
        currentTags.push(selectedTag);
        renderSelectedTags();
        updateTagSelect();
    }
    
    // 重置选择框
    select.value = '';
}

// 添加新标签
function addNewTag() {
    const tagName = prompt('请输入新标签名称:');
    if (tagName && tagName.trim()) {
        const trimmedTag = tagName.trim();
        if (!currentTags.includes(trimmedTag)) {
            currentTags.push(trimmedTag);
            renderSelectedTags();
            updateTagSelect();
        }
    }
}

function removeSelectedTag(tag) {
    const index = currentTags.indexOf(tag);
    if (index > -1) {
        currentTags.splice(index, 1);
        renderSelectedTags();
        updateTagSelect();
    }
}

function renderSelectedTags() {
    const container = document.getElementById('selected-tags');
    
    if (currentTags.length === 0) {
        container.innerHTML = `
            <div class="empty-tags">
                <i class="fas fa-tags"></i>
                暂无选择标签
            </div>
        `;
    } else {
        container.innerHTML = currentTags.map(tag => `
            <div class="selected-tag">
                <span>${tag}</span>
                <button type="button" class="selected-tag-remove" onclick="removeSelectedTag('${tag}')">
            <i class="fas fa-times"></i>
        </button>
            </div>
        `).join('');
    }
}

function updateTagSelect() {
    const select = document.getElementById('tag-select');
    const options = select.querySelectorAll('option');
    
    options.forEach(option => {
        if (option.value && currentTags.includes(option.value)) {
            option.disabled = true;
            option.style.color = '#6c757d';
        } else {
            option.disabled = false;
            option.style.color = '';
        }
    });
}

// 封面图片相关功能
let currentCoverMode = 'none';
let coverImages = [];
let selectedMediaItems = [];

// 设置封面模式
function setCoverMode(mode) {
    currentCoverMode = mode;
    
    // 更新按钮状态
    document.querySelectorAll('.mode-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-mode="${mode}"]`).classList.add('active');
    
    // 更新预览区域
    updateCoverPreview();
    
    // 更新隐藏字段
    document.getElementById('cover_mode').value = mode;
}

// 更新封面预览
function updateCoverPreview() {
    const preview = document.getElementById('cover-preview');
    const removeBtn = document.querySelector('.btn-remove');
    
    // 移除所有模式类
    preview.classList.remove('single-mode', 'triple-mode');
    
    if (currentCoverMode === 'none') {
        preview.innerHTML = `
            <div class="empty">
                <i class="fas fa-ban"></i>
                <p>无封面图片</p>
            </div>
        `;
        preview.classList.add('empty');
        removeBtn.style.display = 'none';
        document.getElementById('cover_image').value = '';
    } else if (currentCoverMode === 'single') {
        preview.classList.add('single-mode');
        preview.classList.remove('empty');
        if (coverImages.length > 0) {
            preview.innerHTML = `<img src="${coverImages[0]}" alt="封面图片">`;
            removeBtn.style.display = 'inline-block';
            document.getElementById('cover_image').value = coverImages[0];
        } else {
            preview.innerHTML = `
                <div class="empty">
                    <i class="fas fa-image"></i>
                    <p>请选择一张图片</p>
                </div>
            `;
            preview.classList.add('empty');
            removeBtn.style.display = 'none';
        }
    } else if (currentCoverMode === 'triple') {
        preview.classList.add('triple-mode');
        preview.classList.remove('empty');
        if (coverImages.length >= 3) {
            preview.innerHTML = coverImages.slice(0, 3).map(img => 
                `<img src="${img}" alt="封面图片">`
            ).join('');
            removeBtn.style.display = 'inline-block';
            document.getElementById('cover_image').value = JSON.stringify(coverImages.slice(0, 3));
        } else {
            preview.innerHTML = `
                <div class="empty">
                    <i class="fas fa-images"></i>
                    <p>请选择三张图片</p>
                </div>
            `;
            preview.classList.add('empty');
            removeBtn.style.display = 'none';
        }
    }
}

// 上传封面图片
function uploadCoverImage(input) {
    if (input.files && input.files[0]) {
        const file = input.files[0];
        const reader = new FileReader();
        
        reader.onload = function(e) {
            const imageUrl = e.target.result;
            if (currentCoverMode === 'single') {
                coverImages = [imageUrl];
            } else if (currentCoverMode === 'triple') {
                coverImages = [imageUrl, '', ''];
            }
            updateCoverPreview();
        };
        
        reader.readAsDataURL(file);
    }
}

// 移除封面图片
function removeCoverImage() {
    coverImages = [];
    updateCoverPreview();
}

// 设置自动保存
function setupAutoSave() {
    autoSaveInterval = setInterval(() => {
        if (isFormChanged()) {
            saveDraft(true); // 静默保存
        }
    }, 30000); // 每30秒自动保存一次
}

// 检查表单是否已更改
function isFormChanged() {
    // 这里可以添加更复杂的变更检测逻辑
    return true;
}

// 设置表单验证
function setupFormValidation() {
    const form = document.getElementById('post-form');
    const titleInput = document.getElementById('title');
    const contentInput = document.getElementById('content');
    
    form.addEventListener('submit', function(event) {
        event.preventDefault();
        savePost();
    });
    
    // 实时验证标题
    titleInput.addEventListener('blur', function() {
        if (!this.value.trim()) {
            this.style.borderColor = '#dc3545';
        } else {
            this.style.borderColor = '#ced4da';
        }
    });
    
    // 实时验证内容
    contentInput.addEventListener('blur', function() {
        const content = this.innerHTML.trim();
        if (!content || content === '<br>' || content === '<div><br></div>') {
            this.style.borderColor = '#dc3545';
        } else {
            this.style.borderColor = '#ced4da';
        }
    });
}

// 保存草稿
function saveDraft(silent = false) {
    const status = document.getElementById('status');
    status.value = 'draft';
    savePost(silent);
}

// 发布文章
function publishPost() {
    const status = document.getElementById('status');
    status.value = 'published';
    savePost();
}

// 保存文章
function savePost(silent = false, retryCount = 0) {
    if (!silent) {
        Utils.notification.show('正在保存...', 'info');
    }
    
    // 检查网络连接
    if (!navigator.onLine) {
        Utils.notification.show('网络连接已断开，请检查网络连接', 'error');
        return;
    }
    
    // 收集表单数据
    const data = {
        title: document.getElementById('title').value.trim(),
        content: document.getElementById('content').innerHTML.trim(),
        excerpt: document.getElementById('excerpt').value.trim(),
        cover_image: document.getElementById('cover_image').value,
        category_id: document.getElementById('category_id').value || null,
        status: document.getElementById('status').value,
        is_featured: document.getElementById('is_featured').checked,
        allow_comments: document.getElementById('allow_comments').checked,
        tags: currentTags
    };
    
    // 验证数据
    if (!data.title) {
        Utils.notification.show('请输入文章标题', 'warning');
        document.getElementById('title').focus();
        return;
    }
    
    if (!data.content || data.content === '<br>' || data.content === '<div><br></div>' || data.content === '') {
        Utils.notification.show('请输入文章内容', 'warning');
        document.getElementById('content').focus();
        return;
    }
    
    // 处理分类ID
    if (data.category_id === '') {
        data.category_id = null;
    } else {
        data.category_id = parseInt(data.category_id);
    }
    
    const url = '{{ url_for("post_api.create_post") if not post else url_for("post_api.update_post", post_id=post.id) }}';
    const method = '{{ "POST" if not post else "PUT" }}';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(response => {
        if (response.success) {
            if (!silent) {
                Utils.notification.show('保存成功', 'success');
                setTimeout(() => {
                    window.location.href = '/admin/posts';
                }, 600);
            }
        } else {
            Utils.notification.show(response.message || '保存失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存失败:', error);
        let errorMessage = '保存失败，请稍后重试';
        
        // 根据错误类型提供更具体的错误信息
        if (error.name === 'TypeError' && error.message.includes('fetch')) {
            errorMessage = '网络连接失败，请检查网络连接';
        } else if (error.name === 'SyntaxError') {
            errorMessage = '服务器响应格式错误';
        }
        
        // 如果是网络错误且重试次数少于3次，自动重试
        if (retryCount < 3 && (error.name === 'TypeError' || !navigator.onLine)) {
            setTimeout(() => {
                Utils.notification.show(`网络错误，正在重试 (${retryCount + 1}/3)...`, 'warning');
                savePost(silent, retryCount + 1);
            }, 2000 * (retryCount + 1)); // 递增延迟
            return;
        }
        
        Utils.notification.show(errorMessage, 'error');
    });
}


// 获取认证令牌
function getAuthToken() {
    // 使用Flask-Login的session认证，不需要token
    return '';
}

// 取消编辑
function cancelEdit() {
    if (isFormChanged()) {
        const isEdit = {{ 'true' if post else 'false'|safe }};
        const message = isEdit ? '您有未保存的更改，确定要离开编辑页面吗？' : '您有未保存的更改，确定要离开新增页面吗？';
        showCustomConfirm(message, function() {
            // 直接跳转到文章管理页面
            window.location.href = '/admin/posts';
        });
    } else {
        // 没有更改，直接跳转
        window.location.href = '/admin/posts';
    }
}

// 显示自定义确认对话框
function showCustomConfirm(message, callback) {
    document.getElementById('confirm-message').textContent = message;
    confirmCallback = callback;
    document.getElementById('custom-confirm').style.display = 'flex';
}

// 隐藏自定义确认对话框
function hideCustomConfirm() {
    document.getElementById('custom-confirm').style.display = 'none';
    confirmCallback = null;
}


// 插入标题
function insertHeading(headingType) {
    if (!headingType) return;
    
    const contentEditor = document.getElementById('content');
    const start = contentEditor.selectionStart;
    const end = contentEditor.selectionEnd;
    const selectedText = contentEditor.value.substring(start, end);
    
    let headingText = '';
    let newCursorPos = start;
    
    if (selectedText) {
        // 如果有选中文本，用标题包装
        headingText = `${headingType.toUpperCase()} ${selectedText}`;
    } else {
        // 如果没有选中文本，插入标题格式
        headingText = `${headingType.toUpperCase()} 标题文本`;
        newCursorPos = start + headingText.length - 4; // 光标放在"标题文本"前
    }
    
    // 替换选中的文本
    const newValue = contentEditor.value.substring(0, start) + headingText + contentEditor.value.substring(end);
    contentEditor.value = newValue;
    
    // 设置新的光标位置
    contentEditor.focus();
    contentEditor.setSelectionRange(newCursorPos, newCursorPos);
    
    // 重置选择框
    event.target.value = '';
}

// 编辑器工具栏功能
function formatText(command) {
    const content = document.getElementById('content');
    const start = content.selectionStart;
    const end = content.selectionEnd;
    const selectedText = content.value.substring(start, end);
    
    let formattedText = '';
    let newCursorPos = start;
    
    if (command === 'bold') {
        if (selectedText) {
            formattedText = `**${selectedText}**`;
        } else {
            formattedText = '****';
            newCursorPos = start + 2;
        }
    } else if (command === 'italic') {
        if (selectedText) {
            formattedText = `*${selectedText}*`;
        } else {
            formattedText = '**';
            newCursorPos = start + 1;
        }
    } else if (command === 'underline') {
        if (selectedText) {
            formattedText = `<u>${selectedText}</u>`;
        } else {
            formattedText = '<u></u>';
            newCursorPos = start + 3;
        }
    }
    
    // 替换选中的文本
    const newValue = content.value.substring(0, start) + formattedText + content.value.substring(end);
    content.value = newValue;
    
    // 设置新的光标位置
    content.focus();
    content.setSelectionRange(newCursorPos, newCursorPos);
}

function insertLink() {
    const url = prompt('请输入链接地址:');
    if (url) {
        const text = prompt('请输入链接文本:', url);
        if (text) {
            insertTextAtCursor(`[${text}](${url})`);
        }
    }
}

function insertImage() {
    const url = prompt('请输入图片地址:');
    if (url) {
        const alt = prompt('请输入图片描述:', '');
        insertTextAtCursor(`![${alt}](${url})`);
    }
}

function insertCode() {
    const code = prompt('请输入代码:');
    if (code) {
        insertTextAtCursor(`\`${code}\``);
    }
}

function insertTextAtCursor(text) {
    const content = document.getElementById('content');
    const start = content.selectionStart;
    const end = content.selectionEnd;
    
    // 替换选中的文本
    const newValue = content.value.substring(0, start) + text + content.value.substring(end);
    content.value = newValue;
    
    // 设置新的光标位置
    content.focus();
    const newCursorPos = start + text.length;
    content.setSelectionRange(newCursorPos, newCursorPos);
}

function insertImage() {
    const url = prompt('请输入图片地址:');
    if (url) {
        const alt = prompt('请输入图片描述:', '');
        insertHtmlAtCursor(`<img src="${url}" alt="${alt}" style="max-width: 100%; height: auto; margin: 0.5rem 0;">`);
    }
}

function insertHtmlAtCursor(html) {
    const contentEditor = document.getElementById('content');
    contentEditor.focus();
    
    const selection = window.getSelection();
    if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        range.deleteContents();
        
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;
        
        const fragment = document.createDocumentFragment();
        while (tempDiv.firstChild) {
            fragment.appendChild(tempDiv.firstChild);
        }
        
        range.insertNode(fragment);
        
        // 将光标移到插入内容之后
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

// 清理定时器
window.addEventListener('unload', function() {
    if (autoSaveInterval) {
        clearInterval(autoSaveInterval);
    }
});
</script>
{% endblock %}
